package com.flow.framework.core.validation.validator;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.common.immutable.Immutable;
import com.flow.framework.common.immutable.annotation.ImmutableRemark;
import com.flow.framework.common.util.clazz.ClazzUtil;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.validation.annotation.ImmutableCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * ImmutableCustomization 校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
@Slf4j
public class ImmutableValidator extends BaseValidator<ImmutableCustomization, Object> {

    private ImmutableCustomization immutableCustomization;

    private Set<Object> immutableConstants = new HashSet<>();

    private String errorMsg;

    @Override
    public void initialize(ImmutableCustomization immutableCustomization) {
        this.immutableCustomization = immutableCustomization;
        Class<? extends Immutable> immutableInterface = immutableCustomization.immutableInterface();
        if (!immutableInterface.isInterface()) {
            log.error("immutable interface isn't interface type. clazz name : {}", immutableInterface.getSimpleName());
            throw new CheckedException(SystemErrorCode.SYSTEM_NOT_SUPPORT_ERROR);
        }
        Field[] fields = immutableInterface.getFields();
        try {
            for (Field field : fields) {
                ImmutableRemark annotation = field.getAnnotation(ImmutableRemark.class);
                if (null == annotation) {
                    log.error("immutable interface field hasn't immutable remark annotation. clazz name : {}", immutableInterface.getSimpleName());
                    throw new CheckedException(SystemErrorCode.SYSTEM_NOT_SUPPORT_ERROR);
                }
                Object o = field.get(null);
                immutableConstants.add(o);
            }
        } catch (Exception e) {
            log.error("construct immutable interface field error. clazz name : {}", immutableInterface.getSimpleName());
            throw new CheckedException(SystemErrorCode.UNEXPECTED_ERROR);
        }
        this.errorMsg = "please refer to the " + ClazzUtil.getShortByClazz(immutableInterface);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }
        if (value instanceof Collection) {
            Collection elements = (Collection) value;
            if (VerifyUtil.isEmpty(elements)) {
                return true;
            }
            elements.forEach(element -> {
                if (!immutableConstants.contains(element)) {
                    super.logError(context, value, errorMsg);
                    throw new ParamCheckedException(immutableCustomization.errorCode());
                }
            });
            return true;
        }
        if (!immutableConstants.contains(value)) {
            super.logError(context, value, errorMsg);
            throw new ParamCheckedException(immutableCustomization.errorCode());
        }
        return true;
    }
}
